﻿using System.Configuration;
using Lync.Widget.Library.Presence;
using Lync.Widget.Library.UserService;

namespace Lync.Widget.Library.Extensions
{
    public static class PresenceExtensions
    {
        public static GroupSubscription OverrideSettings(this GroupSubscription groupSubscription,  Group adGroup, string availability)
        {
            if (adGroup == null)
            {
                groupSubscription.HidePresence = true;
                return groupSubscription;
            }

            var phone = adGroup.Phone;
            var email = adGroup.Email;
            var hidePresence = false;

            if (string.IsNullOrEmpty(phone))
            {
                phone = ConfigurationManager.AppSettings["DistributionGroupPhone"];    
            }

            if (string.IsNullOrEmpty(email))
            {
                email = ConfigurationManager.AppSettings["DistributionGroupEmail"];    
            }

            if (!string.IsNullOrEmpty(availability))
            {
                var status = AvailabilityRangeConverter.Convert(groupSubscription.Availability);
                var availibilityCriteria = AvailabilityCriteriaConverter.Convert(availability);
                hidePresence = (groupSubscription.Availability < 3000
                                            || (availibilityCriteria.Count > 0 && !availibilityCriteria.Contains(status)));
            }
            

            groupSubscription.Email = email;
            groupSubscription.Phone = phone;
            groupSubscription.HidePresence = hidePresence;
           
            return groupSubscription;
        }

        public static PresenceSubscription OverrideSettings(this PresenceSubscription presenceSubscription, User adUser, string availability)
        {            
            bool overrideHideMobile;

            bool.TryParse(ConfigurationManager.AppSettings["AlwaysHideMobilePhone"], out overrideHideMobile);

            if (overrideHideMobile || (adUser != null && adUser.HideMobilePhone))
            {
                presenceSubscription.Mobile = null;
            }
           
            var status = AvailabilityRangeConverter.Convert(presenceSubscription.Availability);
            var availibilityCriteria = AvailabilityCriteriaConverter.Convert(availability);
            presenceSubscription.HidePresence = (presenceSubscription.Availability < 3000 
                || (availibilityCriteria.Count > 0 && !availibilityCriteria.Contains(status)));
            if (presenceSubscription.Availability == 0)
                presenceSubscription.HidePresence = false;
            return presenceSubscription;
        }
    }
}